<?php

namespace Gaolei\YiiRBAC\helpers;

/**
 * Class YiiCache yii 缓存封装
 * @package common\helpers
 */
class Cache
{

    use Singleton;

    const KEEP_TIME = 3600 * 24;

    const RELY_TYPE_FILES = 1;
    const RELY_TYPE_MYSQL = 2;
    const RELY_TYPE_REDIS = 3;

    /**
     * 检测 key 是否存在
     * @param $key
     * @return bool
     * @author: gaolei 2021/1/18 5:47 下午
     */
    public function exists($key): bool
    {
        return \Yii::$app->cache->exists($key);
    }

    /**
     * 设置缓存
     * @param $key
     * @param $value
     * @param int $expire 有效时间 0 永久有效
     */
    public function set($key, $value, int $expire = self::KEEP_TIME)
    {
        $cache = \Yii::$app->cache;
        $cache->set($key, $value, $expire);
    }

    /**
     * 获取指定缓存
     * @param $cache_key
     * @return mixed
     */
    public function get($cache_key)
    {
        $cache = \Yii::$app->cache;
        return $cache->get($cache_key);
    }

    /**
     * 删除指定缓存
     * @param $cache_key
     * @return bool
     */
    public function del($cache_key): bool
    {
        $cache = \Yii::$app->cache;
        return $cache->delete($cache_key);
    }

    /**
     * 修改文件依赖缓存的对应文件 (如果有key 和 data 则新增缓存)
     * @param string $relyFile 依赖文件名
     * @param null $cacheKey
     * @param null $cacheData
     * @param int $expire 有效时间 0 永久有效
     */
    public function setRelyFile(string $relyFile, $cacheKey = null, $cacheData = null, int $expire = self::KEEP_TIME)
    {
        $baseDir = \Yii::getAlias('@temp') . '/cache_rely/';
        $filePath = $baseDir . $relyFile;
        if(!file_exists($filePath) || !$cacheKey){
            try {
                $this->createFolder($baseDir);
                file_put_contents($filePath, print_r(time(), true));
                chmod($filePath, 0777);
            } catch (\Exception $e) {
                \Yii::error($e->getMessage());
            }
        }
        if ($cacheKey && $cacheData) {
            $dependency = new \yii\caching\FileDependency(['fileName' => $filePath]);
            \Yii::$app->cache->set($cacheKey, $cacheData, $expire, $dependency);
        }
    }

    /**
     * 创建文件夹 赋予 0777
     * @param $path
     */
    public function createFolder($path)
    {
        if (!file_exists($path)) {
            self::createFolder(dirname($path));
            if (!mkdir($path, 0777, true) && !is_dir($path)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $path));
            }
            chmod($path, 0777);
        }
    }

}